package com.sky.mall.product.exception;

import com.sky.common.exception.BizCodeEmum;
import com.sky.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice(basePackages = "com.sky.mall.product.controller")
public class MallControllerExceptionAdvice {

    /**
     * 统一的参数校验异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error(e.getMessage());
        //增加表单后台校验
        BindingResult result = e.getBindingResult();
        Map<String, String> errorMessageMap = new HashMap<>();
        result.getFieldErrors().forEach(
                (error) -> {
                    errorMessageMap.put(error.getField(), error.getDefaultMessage());
                });
        return R.error(BizCodeEmum.METHOD_ARGRUMENT_VALID_ERROR.getCode(), BizCodeEmum.METHOD_ARGRUMENT_VALID_ERROR.getMessage())
                .put("data", errorMessageMap);
    }

    /**
     * 处理其他异常
     *
     * @param throwable
     * @return
     */
    @ExceptionHandler(value = Throwable.class)
    public R handleThrowable(Throwable throwable) {
        return R.error(BizCodeEmum.UNKNOW_ERROR.getCode(), BizCodeEmum.UNKNOW_ERROR.getMessage());
    }


}
